﻿$.urlParams = function () {
    var queryParameters = {}, queryString = location.search.substring(1),
        re, m;
    re = /([^&=]+)=([^&]*)/g;

    // Creates a map with the query string parameters
    while (m = re.exec(queryString)) {
        queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]).replace(/\+/g, " ");
    }
    return queryParameters;
};

// Script Search Form
function CMDecodeURIComponent(uri) {
    return uri.replace(/\+/g, " ")
        .replace(/(\%3A)/g, ":")
        .replace(/(\%2C)/g, ",")
        .replace(/(\%2F)/g, "/")
        .replace(/(\%7C)/g, "|");
}

//------------------------------------------------
// Function Name : Trim 
// Actions : Remove left&right space.
//------------------------------------------------
function Trim(temp) {
    if (temp == '')
        return temp;

    temp = temp + '';
    return RTrim(LTrim(temp));
}
//------------------------------------------------
// Function Name : LTrim 
// Actions : Remove left string.
//------------------------------------------------
function LTrim(temp) {
    if (temp == '')
        return temp;

    return temp.replace(/^\s+/, '');
}

//------------------------------------------------
// Function Name : RTrim 
// Actions : Remove right space.
//------------------------------------------------
function RTrim(temp) {
    if (temp == '')
        return temp;
    return temp.replace(/\s+$/, '');
}
function getParametterFormTextbox(elem) {

    var $input = $(elem);
    //return $input.val();

    if ($input.length > 0) {
        var queryString = $input.val();
        queryString = Trim(queryString);
        queryString = queryString.replace(/\s+/g, ' ');
        queryString = queryString.replace(/\s/g, '-');
        queryString = queryString.replace(/[^0-9a-zA-Z\-\_áàảãạăắằẳẵặâấầẩẫậóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựđíìỉĩịéèẻẽẹêếềểễệýỳỷỹỵÁÀẢÃẠĂẮẰẲẴẶÂẤẦẨẪẬÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰĐÍÌỈĨỊÉÈẺẼẸÊẾỀỂỄỆÝỲỶỸỴ]/g, '');
        queryString = queryString.replace(/-+/g, '-');

        return queryString;
    }
    return "";
}
function FormatCurrency(num, currencyCode, isReplace, justFormat) {
    if (num == null)
        return "";
    if (currencyCode == null)
        currencyCode = 'vi-vn';
    var num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    var sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3) ; i++) {
        switch (Trim(currencyCode.toLowerCase())) {
            case 'en-us':
                {
                    num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
                    break;
                }
            case 'vi-vn':
                {
                    num = num.substring(0, num.length - (4 * i + 3)) + '.' + num.substring(num.length - (4 * i + 3));
                    break;
                }
        }
    }
    var res = '0';
    switch (Trim(currencyCode.toLowerCase())) {
        case 'en-us':
            {
                if (justFormat != null && justFormat == true) {
                    if (isReplace == false)
                        res = (((sign) ? '' : '-') + num + '.' + cents);
                    else
                        res = (((sign) ? '' : '-') + num);
                }
                else {
                    if (isReplace == false)
                        res = (((sign) ? '' : '-') + '$' + num + '.' + cents);
                    else
                        res = (((sign) ? '' : '-') + '$' + num);
                }
                break;
            }
        case 'vi-vn':
            {
                if (justFormat != null && justFormat == true) {
                    if (isReplace == false)
                        res = (((sign) ? '' : '-') + num + ',' + cents);
                    else
                        res = (((sign) ? '' : '-') + num);
                }
                else {
                    if (isReplace == false)
                        res = (((sign) ? '' : '-') + num + ',' + cents + 'đ');
                    else
                        res = (((sign) ? '' : '-') + num + 'đ');
                }
                break;
            }
    }
    return res;
}
/***************Home : Like/Dislike, popup menu************/
var $initHomePage = function (cityCookieName, cityId, domain) {
    $(function () {
//        initPopupMenu('div.div_btn_city', 'div.list_city');
        initPopupMenu('div.div_list_hotline', 'div.div_hot_line');
//        initPopupMenu('div.div_cart_login_register', '.class_list_login_register');
//        initPopupMenu('.div_targetLike', '.class_list_like');
//        initPopupMenu('div.div_cart_buy', '.class_list_cart');

        $('.btn_top').click(function () {
            $("html, body").animate({ scrollTop: 0 }, 10);
            return false;
        });

        $('.btn_down').click(function () {
            $("html, body").animate({ scrollTop: $(document).height() }, 10);
            return false;
        });

        $('#closeChoosenCity').click(function () {
            $.cookie(cityCookieName, cityId, { expires: 10000, domain: domain, path: '/' });
            $('div.boxTooltipchooseCity').hide();
        });
        
        $("#topcontrol").css("left", parseFloat($('.header').offset().left) + parseFloat($('.header').width()) + 22);
        $(window).resize(function () {
            $("#topcontrol").css("left", parseFloat($('.header').offset().left) + parseFloat($('.header').width()) + 22);
        });
    });
};

$(window).scroll(function () {
    if ($(this).scrollTop() > 100) {
        var $top = $('#topcontrol');
        $top.fadeIn();
    } else {
        $('#topcontrol').fadeOut();
    }
});

// Thong.Nguyen : khoi tao popup
function initPopupMenu(menu, popup, timeout) {
    var t = null;
    if (!timeout) { timeout = 200; }
    $(menu).mouseover(function (e) {
        e.preventDefault();
        //console.log(t + ' over');
        if (t != null) { clearTimeout(t); }
        $(popup).show();
    });
    $(menu).mouseout(function (e) {
        e.preventDefault();
        t = setTimeout(function () {
            $(popup).hide();
        }, timeout);
        //console.log(t + ' out');
    });
}

// Thong.Nguyen : Like/Unlike
function DoLike(obj, pid, useEffect) {
    if ($(obj).hasClass('disabled')) {
        return false;
    }
    ;
    $(obj).addClass('disabled');

    // config value
    var $targetLike = $('#targetLike');
    var $flyObject = $('#likeContainer');
    var productLikeName = 'ProductLike';
    var urlLike = '/like';
    var urlUnlike = '/unlike';
    var isLiked = false;

    var cookieValue = getCookie(productLikeName);
    if (cookieValue.length > 0) {
        $.each(cookieValue.split(','), function (key, item) {
            if ($.trim(item).indexOf(pid) > -1) {
                var state = item.substr($.trim(item).length - 1, 1);
                if (state == 0 || state == 2) {
                    isLiked = true;
                } else {
                    isLiked = false;
                }
                return false;
            }
        });
    }
    var posX = $targetLike.offset().left + 5;
    var posY = $targetLike.offset().top + 15;
    //posX = 1294;
    //posY = 15;

    var pX = $(obj).offset().left + 5;
    var pY = $(obj).offset().top + 2;

    if (isLiked) {
        var pos = posX;
        posX = pX;
        pX = pos;

        pos = posY;
        posY = pY;
        pY = pos;

        // Do UnLike
        $(obj).removeClass('active');
        requestLike('unlike', urlUnlike, { productId: pid, customerId: 0 });
    } else {
        // Do like
        $(obj).addClass('active');
        requestLike('like', urlLike, { productId: pid, customerId: 0 });
    }

    if (useEffect) {
        $flyObject.css({ position: 'absolute', top: pY, left: pX, display: "block" })
            .animate({ top: posY, left: posX }, 1000, function () {
                $flyObject.hide();
                $(obj).removeClass('disabled');
            });
    }
}

// Thong.Nguyen : Do request Like/Unlike
var requestAjaxLike;
function requestLike(type, url, param) {
    if (requestAjaxLike) {
        requestAjaxLike.abort();
    }
    // Do Post Request
    requestAjaxLike = $.ajax({
        type: 'post',
        url: url,
        data: param
    });
    requestAjaxLike.done(function (response) {
        //Update menu
        var span = $('#list_likebox_content span:first');
        if (response.TotalLike > 0) {
            $('#list_likebox_content').html(response.Menu);
            span.find('b').html('Sản phẩm yêu thích');
            $('#list_likebox_content').prepend(span);
        } else {
            $('#list_likebox_content').html(response.Menu);
            span.find('b').addClass('empty').html('Không có sản phẩm yêu thích');
            $('#list_likebox_content').prepend(span);
        }
    });
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}
/***************End Home : Like/Dislike, popup menu************/

/***************Slide Banner*******************/
function HotDealView(id, indexOnCurrent) {
    this.section = $('li', id);
    this.lefts = $('strong a', this.section);
    this.rights = $('em a', this.section);
    this.indexOnCurrent = indexOnCurrent - 1;
    this.initFlag = false;
};

HotDealView.prototype.init = function () {
    if (this.initFlag) {
        return;
    }
    var $this = this;
    $this.on(this.indexOnCurrent);
    $this.rights.mouseover(function () {
        //console.log($this.rights);
        var index = $this.rights.index(this);
        $this.on(index);
    });
    this.initFlag = true;
};

HotDealView.prototype.on = function (index) {
    index = index % this.rights.size();
    this.section.removeClass('sected').eq(index).addClass('sected');
    this.indexOnCurrent = index;
    return index;
};

function RollingHotDealView(view) {
    this.view = view;
    this.timesOnRolling = view.indexOnCurrent;
    this.timeForInterval = -1;
    this.view.init();
};

RollingHotDealView.prototype.start = function (interval) {
    interval = interval || 3000;
    var $this = this;
    $this.view.lefts.mouseover(function () {
        $this.shutdown();
    }).mouseout(function () {
        $this.timeForInterval = setInterval(function () {
            $this.view.on($this.timesOnRolling++);
        }, interval);
    });
    $this.view.rights.mouseover(function () {
        $this.timesOnRolling = $this.view.rights.index(this) + 1;
        $this.shutdown();
    }).mouseout(function () {
        $this.timeForInterval = setInterval(function () {
            $this.view.on($this.timesOnRolling++);
        }, interval);
    });

    $this.timeForInterval = setInterval(function () {
        $this.view.on($this.timesOnRolling++);
    }, interval);
};

RollingHotDealView.prototype.shutdown = function () {
    clearInterval(this.timeForInterval);
};
/***************End Slide Banner*******************/

/***************Category Menu*******************/
var $bindMenuCate = function (categoryId) {
    $(function () {
        var t = null;

        //$('div.cate_div a:gt(1), div.cate_child_div').mouseover(function (e) {
        $('div.title_cate_div').slice(1,9).mouseover(function (e) {
            e.preventDefault();
            //console.log(t + ' over');
            if (t != null) {
                clearTimeout(t);
            }
            //if (!$(this).hasClass('cate_child_div')) {
            //    var objClassName = $(this).attr('class');
            //    objClassName = objClassName.substr(objClassName.indexOf('cate_'), objClassName.length);
            //    // Hide all submenu item except item index 1
            //    $('div.cate_child_div ul li:gt(0)').addClass('hidden');
            //    // Show items relation with object hover
            //    $('li.sub' + objClassName).removeClass('hidden');
            //    var marginLeft = parseInt(objClassName.replace(/^\D+/g, ''));
            //    if (!marginLeft) marginLeft = 0;
            //    $('div.cate_child_div ul').css({ marginLeft: marginLeft });
            //    $('div.cate_child_div ul li:eq(0) a').attr('href', $(this).attr('href'));
            //}
            //$('div.cate_child_div').show();
            $('div.cate_div').find('div.div_list_title').hide();
            var aMenu = $(this).find('a.ico_cate');
            if (!aMenu.hasClass('active')) {
                $(this).find('li:eq(0) a:eq(0)').attr('href', aMenu.attr('href'));
                $(this).find('div.div_list_title').show();
            }
        });
        //$('div.cate_div a:gt(1), div.cate_child_div').mouseout(function (e) {
        $('div.title_cate_div').slice(1, 9).mouseout(function (e) {
            e.preventDefault();
            t = setTimeout(function () {
                //if (categoryId == 0) {
                //    // hide submenu if not is category page
                //    $('div.cate_child_div').hide();
                //} else {
                //    var objClassName = $('div.cate_div a.active').attr('class');
                //    objClassName = objClassName.substr(objClassName.indexOf('cate_'), objClassName.length);
                //    // Hide all submenu item except item index 1
                //    $('div.cate_child_div ul li:gt(0)').addClass('hidden');
                //    // show current submenu
                //    $('li.sub' + objClassName).removeClass('hidden');
                //    var marginLeft = parseInt(objClassName.replace(/^\D+/g, ''));
                //    if (!marginLeft) marginLeft = 0;
                //    $('div.cate_child_div ul').css({ marginLeft: marginLeft });
                //    // catch position window have scroll
                //    if ($(window).scrollTop() > 165) {
                //        $('div.cate_child_div').hide();
                //    }
                //}
                //$(this).find('div.cate_div').find('div.div_list_title').hide();
                $(e.currentTarget).find('div.div_list_title').hide();
            }, 50);
        });
        // set subcate menu position
        var objActiveClassName = $('div.cate_div a.active');
        if (objActiveClassName.length > 0) {
            objActiveClassName = $('div.cate_div a.active').attr('class');
        } else {
            objActiveClassName = $('div.cate_div a:eq(0)').attr('class');
        }
        objActiveClassName = objActiveClassName.substr(objActiveClassName.indexOf('cate_'), objActiveClassName.length);
        $('div.cate_child_div ul').css({ marginLeft: parseInt(objActiveClassName.replace(/^\D+/g, '')) });
        $('#aCateSubAll').attr('href', $('div.cate_div a.active').attr('href'));
        
        // handel event window scroll
        $(window).scroll(function (e) {
            var pY = $(window).scrollTop();
            //var floatMenuY = $('div.cate_div:eq(0)').offset().top;
            if (pY > 165) {
                $('div.header_div:eq(0)').hide();
                $('div.cate_child_div:eq(0)').hide();
                $('div.cate_div:eq(0)').addClass('shadow');
            } else {
                $('div.cate_div:eq(0)').removeClass('shadow');
                $('div.header_div:eq(0)').show();
                if (categoryId > 0) {
                    $('div.cate_child_div:eq(0)').show();
                }
            }
        });
    });
};
/***************End Category Menu*******************/

/*****************category Search******************/
$(function() {
    //------checkbox filter click------//
    $(".body_cate_content input[type='checkbox']").click(function() {
        var lastFilter = $(this).val();
        if (lastFilter.indexOf(':') > 0) {
            lastFilter = lastFilter.split(':')[0];
        }
        reloadFilter(lastFilter);
    });

    //-------View more cate menu--------//
    $('.view_more_cate').click(function () {
        var tr = $('.' + $(this).attr('id'));
        if ($(this).hasClass('ShowFullMenu')) {
            $(this).removeClass('ShowFullMenu');
            $($(this).find('span')[0]).html('Xem thêm');
            $($(this).find('span')[1]).removeClass('view_more_up').addClass('view_more');

            $(tr).addClass('hidden');
        } else {
            $(this).addClass('ShowFullMenu');
            $($(this).find('span')[0]).html('Thu gọn');
            $($(this).find('span')[1]).addClass('view_more_up').removeClass('view_more');
            $(tr).removeClass('hidden');
        }
        //console.log($(this).closest('ul'));
    });

    //---------Load more product in cate-----//
    $('#elLoadMoreProductInCate').click(function () {
        DoLoadMoreProductInCate(this);
        return false;
    });
});

function reloadFilter(lastFilter) {
    var urlParams = $.urlParams();
    //if (lastFilter == undefined || lastFilter == "") {
    //    lastFilter = urlParams["lf"];
    //}

    var isLastfilterIsValid = false;
    var filterQueryParam = "";
    var groups = [];
    var checkBoxsChecked = $("input.filterCheckbox:checked").each(function (index, element) {
        var attrValues = $(this).val().split(':');
        if (jQuery.inArray(attrValues[0], groups) < 0) {

            groups.push(attrValues[0]);
            if (filterQueryParam != "")
                filterQueryParam += "/";
            filterQueryParam += attrValues[0] + ":";

        }

        filterQueryParam += decodeURIComponent(attrValues[1]) + "|";
        if (attrValues[0] == lastFilter) {
            isLastfilterIsValid = true;
        }
    });
    filterQueryParam = filterQueryParam.replace(/\|\//g, '/');  //replace '|/' to '/'
    filterQueryParam = filterQueryParam.replace(/\|$/, '');     // remove '/' at the end
    if (filterQueryParam == "") {
        delete urlParams["f"];
    }
    else {
        urlParams["f"] = filterQueryParam;
    }

    if (lastFilter != "" && lastFilter != undefined && isLastfilterIsValid) {
        urlParams["lf"] = lastFilter;
    }

    if (!isLastfilterIsValid) {
        delete urlParams["lf"];
    }
    delete urlParams["p"];
    delete urlParams["gf"];

    var pathName = window.location.pathname;
    var url = window.location.protocol + "//" + window.location.host + pathName;
    if (countAttribute(urlParams) > 0)
        url = url + "?" + CMDecodeURIComponent($.param(urlParams));
    window.location = url;
}

$.urlParams = function () {
    var queryParameters = {}, queryString = location.search.substring(1),
        re, m;
    re = /([^&=]+)=([^&]*)/g;

    // Creates a map with the query string parameters
    while (m = re.exec(queryString)) {
        queryParameters[decodeURIComponent(m[1])] = decodeURIComponent(m[2]).replace(/\+/g, " ");
    }
    return queryParameters;
};

function countAttribute(obj) {
    var count = 0;
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop))
            count = count + 1;
    }
    return count;
}

//-------------------Load more cate-------------------
var cate_loadmoreRequest;
var cate_currentPage = 2;
function DoLoadMoreProductInCate(obj) {
    if ($(obj).hasClass('active')) { return; }
    if (cate_loadmoreRequest) {
        cate_loadmoreRequest.abort();
    }
    // Disable click button
    var labelText = $(obj).html();
    //$(obj).html('<img alt="Đang tải dữ liệu" style="float:left;height:25px" src="/Content/Images/ajax-loader.gif"/></span>Vui lòng chờ');
    $(obj).text('Vui lòng chờ');

    // Do Post Request
    cate_loadmoreRequest = $.ajax({
        type: 'post',
        url: $(obj).attr('href'),
        data: { page: cate_currentPage }
    });
    cate_loadmoreRequest.done(function (response) {
        $(obj).removeClass('active');

        $(obj).html(labelText);
        $('#ul_List_deal_category').append(response.html);
        $('#boxCateBottomPager').html(response.pageSize + '/' + response.totalItem);
        cate_currentPage++;
        if (response.pageSize >= response.totalItem) {
            //console.log('hide load more');
            $('p.txt_center').hide();
        }
    });
}

function isDate(txtDate, separator) {
    var aoDate,           // needed for creating array and object
        ms,               // date in milliseconds
        month, day, year; // (integer) month, day and year
    // if separator is not defined then set '/'
    if (separator === undefined) {
        separator = '/';
    }
    // split input date to month, day and year
    aoDate = txtDate.split(separator);
    // array length should be exactly 3 (no more no less)
    if (aoDate.length !== 3) {
        return false;
    }
    // define month, day and year from array (expected format is m/d/yyyy)
    // subtraction will cast variables to integer implicitly
    month = aoDate[0] - 1; // because months in JS start from 0
    day = aoDate[1] - 0;
    year = aoDate[2] - 0;
    // test year range
    if (year < 1000 || year > 3000) {
        return false;
    }
    // convert input date to milliseconds
    ms = (new Date(year, month, day)).getTime();
    // initialize Date() object from milliseconds (reuse aoDate variable)
    aoDate = new Date();
    aoDate.setTime(ms);
    // compare input date and parts from Date() object
    // if difference exists then input date is not valid
    if (aoDate.getFullYear() !== year ||
        aoDate.getMonth() !== month ||
        aoDate.getDate() !== day) {
        return false;
    }
    // date is OK, return true
    return true;
}
/*****************End category Search******************/